import axios from "axios";
import { getToken } from "@/utils/auth";
import qs from "qs";
const mimeMap = {
  zip: "application/zip",
  pdf: "application/pdf",
  png: "application/png",
  jpg: "image/jpeg",
  jpeg: "image/jpeg",
  xls: "application/vnd.ms-excel",
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  csv: "application/csv",
  doc: "application/msword",
  docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  bmp: "image/bmp",
  gif: "image/gif",
};

const baseUrl = process.env.VUE_APP_BASE_API;

export function downLoadZip(uri, data, map, fileName) {
  var url = baseUrl + uri;
  axios({
    method: "POST",
    url: url,
    responseType: "blob",
    data: qs.stringify(data),
    headers: {
      Authorization: getToken(),
      "content-type": "application/x-www-form-urlencoded",
    },
  }).then((res) => {
    resolveBlob(res.data, map, fileName);
  });
}

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容   直接返回的bolb内容。不用res.data
 * @param {String} mimeType MIME类型
 */
export function resolveBlob(res, map, filename) {
  console.log("res: ", res);
  if (!filename) filename = "下载";
  const aLink = document.createElement("a");
  var blob = new Blob([res], { type: mimeMap[map] });
  // 视情况而定
  // 1.从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  // var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  // var contentDisposition = decodeURI(res.headers['content-disposition'])
  // var result = patt.exec(contentDisposition)
  // var fileName = result[1]
  // fileName = fileName.replace(/\"/g, '')
  aLink.href = URL.createObjectURL(blob);
  // 2.直接使用自定义文件名
  aLink.setAttribute("download", filename); // 设置下载文件名称
  document.body.appendChild(aLink);
  aLink.click();
  document.body.removeChild(aLink);
}

/**
 * 解析a标签下载
 * @param {*} res  下载地址
 * @param {String}
 */
export function resolveHref(url, filename) {
  if (!filename) filename = "下载";
  const aLink = document.createElement("a");
  aLink.href = url;
  // 2.直接使用自定义文件名
  // aLink.setAttribute('download', filename) // 设置下载文件名称
  aLink.download = filename; //这种写法有个前提：href 的下载地址 和 当前网站地址 必须是 同源的，否则download不生效。
  document.body.appendChild(aLink);
  aLink.click();
  document.body.removeChild(aLink);
}
